use std::process::Command;

fn main() {
//     命令注入防护
    let ls = "ls -hla /tmp";
    safe_command_execution(ls).unwrap();

    let cp = "cp aa bb";
    safe_command_execution(cp).unwrap();
}
fn safe_command_execution(user_input: &str) -> Result<(), Box<dyn std::error::Error>> {
//     不要直接拼接命令字符串
    let args: Vec<&str> = user_input.split_whitespace().collect();
    if args.is_empty() {
        return Err("Empty command".into());
    }
    // 验证命令和参数
    let command = args[0];
    let whitelist = ["ls", "cat", "echo"];

    if !whitelist.contains(&command) {
        return Err("Command not allowed".into());
    }
    let output = Command::new(command)
        .args(&args[1..])
        .output()?;
    println!("Output:{}", String::from_utf8_lossy(&output.stdout));
    Ok(())
}